//
//  UITextView+Extension.swift
//  emoticonKeyboard
//
//  Created by 王洪运 on 15/11/30.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit


extension UITextView {
    
    var emoticonText: String {
        
        let attrString = attributedText
        var strM = String()
        
        attrString.enumerateAttributesInRange(NSRange(location: 0, length: attrString.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? WHYEmoticonAttachment {
                strM += attachment.emoticon.chs ?? ""
            }else {
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        return strM
        
    }
    
    func insertEmoticon (emoticon: WHYEmoticon) {
        if emoticon.isEmpty {
            return
        }
        
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        if let emoji = emoticon.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        
        insertImageEmoticon(emoticon)
        
//        不能用强制解包，因为代理方法可能没实现或没有代理
        delegate?.textViewDidChange?(self)
    }
    
    
    private func insertImageEmoticon(emoticon:WHYEmoticon) {
        
        let imageText = WHYEmoticonAttachment(emoticon: emoticon).imageText(font!)
        
        //        获取textView的属性文本
        let textM = NSMutableAttributedString(attributedString: attributedText)
        //        替换属性文本内容
        let range = selectedRange
        textM.replaceCharactersInRange(range, withAttributedString: imageText)
        //        更新textView的属性文本
        attributedText = textM
        //        移动光标到文本末尾
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
    }

    
}
